package com.xqboss.apps.listener;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xqboss.apps.constant.RedisKey;
import com.xqboss.apps.domain.hama.HamaHelp;
import com.xqboss.apps.domain.hama.HamaMixLog;
import com.xqboss.apps.domain.hama.HamaUserMix;
import com.xqboss.apps.enums.hama.HamaConfigNumberPeopleEnum;
import com.xqboss.apps.enums.hama.HamaConfigNumberTypeEnum;
import com.xqboss.apps.enums.hama.HamaMixLogHireEnum;
import com.xqboss.apps.enums.mq.AppMqDelayEnum;
import com.xqboss.apps.enums.user.WalletLidouChangeTypeEnum;
import com.xqboss.apps.mapper.hama.HamaHelpMapper;
import com.xqboss.apps.service.hama.HamaConfigNumberService;
import com.xqboss.apps.service.hama.HamaMixLogService;
import com.xqboss.apps.service.hama.HamaUserMixService;
import com.xqboss.apps.util.mh.MoneyUtils;
import com.xqboss.common.core.mq.MqEnum;
import com.xqboss.common.core.mq.MqListener;
import com.xqboss.common.core.redis.lock.RedisLockUtils;
import com.xqboss.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.rocketmq.client.apis.consumer.ConsumeResult;
import org.apache.rocketmq.client.apis.message.MessageView;
import org.redisson.api.RReadWriteLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 运动场装备手环空投力豆
 *
 * @author ljh
 * @date 2024/3/1
 */
@Slf4j
@Component
public class SportMixListener extends MqListener {

    @Autowired
    private RedisLockUtils redisUtil;

    @Autowired
    private HamaHelpMapper hamaHelpMapper;

    @Autowired
    private HamaConfigNumberService hamaConfigNumberService;

    @Autowired
    private HamaMixLogService hamaMixLogService;

    @Autowired
    private HamaUserMixService hamaUserMixService;


    @Override
    public MqEnum getEnum() {
        return AppMqDelayEnum.SPORT_MIX;
    }

    @Override
    public ConsumeResult solve(MessageView message) {
        String value = StandardCharsets.UTF_8.decode(message.getBody()).toString();
        List<Long> userIds= JSONArray.parseArray(value, Long.class);
        Date date = Date.from(LocalDateTime.now().truncatedTo(ChronoUnit.HOURS).atZone(ZoneId.systemDefault()).toInstant());//当前整点小时
        airdropMix(userIds,date);
        return ConsumeResult.SUCCESS;
    }


    public void airdropMix(List<Long> userIds,Date indexTime) {
        log.info("------- time:{}; hama-init-user-mix:{}",indexTime, userIds);
        if(CollectionUtils.isNotEmpty(userIds)){
            for (int i=0;i<userIds.size();i++){
                Long userId=userIds.get(i);
                RReadWriteLock lock = redisUtil.getRedissonClient().getReadWriteLock(RedisKey.SPORT_AIRDROP_MIX + userId);
                try {
                    boolean tryLock = lock.writeLock().tryLock();
                    if (!tryLock) {
                        return;
                    }
                    HamaUserMix mix=hamaUserMixService.getOne(Wrappers.<HamaUserMix>lambdaQuery().eq(HamaUserMix::getUserId,userId));
                    List<HamaMixLog> hamaMixLogList=hamaMixLogService.list(Wrappers.<HamaMixLog>lambdaQuery()
                            .eq(HamaMixLog::getUserId,mix.getUserId())
                            .eq(HamaMixLog::getIsHire, HamaMixLogHireEnum.YES)
                    );
                    if(CollectionUtils.isEmpty(hamaMixLogList)){
                        mix.setBasicSpeed(BigDecimal.ZERO);
                        mix.setNumber(0);
                        hamaUserMixService.updateById(mix);
                    }else {
                        // 过期蛤蟆卡数量
                        int hamaNumber=0;
                        //查询每个用户使用的卡是否过期
                        List<HamaMixLog> updateLog=new ArrayList<>();
                        for (HamaMixLog hamaMixLog : hamaMixLogList) {
                            int hireTime = (int) DateUtils.subtractMin(hamaMixLog.getHireTime(), indexTime);
                            if(hireTime<1){
                                hamaMixLog.setIsHire(HamaMixLogHireEnum.NO);
                                updateLog.add(hamaMixLog);
                                hamaNumber=hamaNumber+hamaMixLog.getHamaNumber();
                            }
                        }
                        if(CollectionUtils.isNotEmpty(updateLog)){
                            hamaMixLogService.updateBatchById(updateLog);
                        }
                        int time = (int) DateUtils.subtractMin(indexTime,mix.getStartProductionTime());// 距离上一次空投多少分钟
                        if(time>0){
                            // 根据 运动场投放装备蛙星人倍率 获取实际空投速率
                            BigDecimal num = MoneyUtils.multipleToScale6(mix.getBasicSpeed(), DateUtils.minToHour(time));// 计算当前用户的收益（这段时间-分钟）
                            mix.setEggLayingNum(MoneyUtils.add(mix.getEggLayingNum(),num));
                            mix.setStartProductionTime(indexTime);
                            hamaUserMixService.updateById(mix);
                            //添加到仓库
                            hamaUserMixService.addIncome(mix.getUserId(),mix.getId(),num, WalletLidouChangeTypeEnum.SPORT_MIX_INCOME);
                        }
                        //存在蛤蟆卡过期，需要重新计算速度和卡的数量
                        HamaHelp hamaHelp= hamaHelpMapper.selectOne(Wrappers.<HamaHelp>lambdaQuery().eq(HamaHelp::getChildUserId,mix.getUserId()));
                        if(hamaNumber>0){
                            if(hamaNumber-mix.getNumber()>=0){
                                mix.setBasicSpeed(BigDecimal.ZERO);
                                mix.setNumber(0);
                                hamaUserMixService.updateById(mix);
                                //修改助力速度
                                if(ObjectUtils.isNotEmpty(hamaHelp)){
                                    // 修改用户最新速度 助力速度
                                    hamaHelp.setBasicSpeed(BigDecimal.ZERO);
                                    hamaHelp.setNumber(0);
                                    hamaHelpMapper.updateById(hamaHelp);
                                }
                            }else {
                                hamaNumber=mix.getNumber()-hamaNumber;//有效已投放装备数量
                                Integer waNumber = hamaUserMixService.getWaNumber(mix.getUserId());//有效的蛙星人数量
                                BigDecimal basicSpeed = hamaConfigNumberService.getBasicSpeed(HamaConfigNumberTypeEnum.ONE, HamaConfigNumberPeopleEnum.OLD, waNumber);
                                mix.setBasicSpeed(basicSpeed);
                                mix.setNumber(hamaNumber);
                                hamaUserMixService.updateById(mix);
                                //修改助力速度
                                if(ObjectUtils.isNotEmpty(hamaHelp)){
                                    // 修改用户最新速度 助力速度
                                    BigDecimal basicSpeed1 = hamaConfigNumberService.getBasicSpeed(HamaConfigNumberTypeEnum.TWO, HamaConfigNumberPeopleEnum.OLD, waNumber);
                                    hamaHelp.setBasicSpeed(basicSpeed1);
                                    hamaHelp.setNumber(hamaNumber);
                                    hamaHelpMapper.updateById(hamaHelp);
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                } finally {
                    if (lock.writeLock().isLocked()) {
                        if (lock.writeLock().isHeldByCurrentThread()) {
                            lock.writeLock().unlock();
                        }
                    }
                }
            }
        }
    }
}